Ext.define('MyApp.controller.role.RoleController', {
	extend : 'MyApp.controller.share.BaseGridController',
	views : ['role.RoleView', 'role.RoleForm', 'role.UserGridView',
			'role.SearchUserGridView', 'role.AuthorityTreeView',
			'role.AuthorityTreeWindow'],
	stores : ['RoleStore', 'RoleSearchUserStore', 'AuthorityTreeStore'],
	models : ['UserEntity', 'RoleEntity'],
	requires : ['Ext.ux.ProgressBarPager'],
	refs : [{
				ref : 'roleview',
				selector : 'roleview'
			}, {
				ref : 'usergridview',
				selector : 'usergridview'
			}, {
				ref : 'deleteuserbtn',
				selector : 'usergridview button#deleteuser'
			}],
	authoritytreeload : false,
	init : function() {
		this.control({

			'roleview' : {
				select : function() {
					this.onGridSelect(this.getRoleview());
				},
				deselect : function() {
					this.onGridDSelect(this.getRoleview());
				}
			},
			'usergridview grid' : {
				select : function() {
					this.getDeleteuserbtn().setDisabled(false);
				},
				deselect : function() {
					this.getDeleteuserbtn().setDisabled(true);
				}
			},
			'usergridview button#deleteuser' : {
				click : function(btn) {
					var me = this;
					Ext.MessageBox.confirm('提示', '确定要删除此记录吗?',
							function showResult(btnResult) {
								if (btnResult == 'yes') {
									var record = me.getRoleview()
											.getSelectionModel()
											.getLastSelected(), records = btn
											.up('usergridview').down('grid')
											.getSelectionModel().getSelection(), userstore = me
											.getUsergridview().down('grid')
											.getStore();
									if (records.length > 0) {
										var arr = new Array();
										for (var i = 0; i < records.length; i++) {
											arr.push(records[i].getData());
										}
										Ext.Ajax.request({
											url : 'role/deleteUserForRole',
											jsonData : Ext.encode(arr),
											params : {
												roleId : record.get('id')
											},
											success : function(response) {
												var text = response.responseText;
												if (text == 1) {
													userstore.remove(records);
													Ext.MessageBoxUtil.msg(
															'提示', '删除成功!');
												} else {
													Ext.MessageBoxUtil.msg(
															'提示', '删除失败!');
												}
											},
											failure : function(response,
													options) {
												Ext.MessageBoxUtil
														.msg(
																'提示',
																'操作失败,错误编号：'
																		+ response.status);
											}
										});
									}
								}
							});
				}
			},
			'roleview button#editauthority' : {
				click : function(btn) {
					var record = btn.up('roleview').getSelectionModel()
							.getLastSelected(), win = Ext.widget(
							'authoritytreewindow', {
								animateTarget : document.body
							});
					win.setTitle('角色 ' + record.get('roleDescription')
							+ ' 对应的权限');
					win.show();
				}
			},
			'authoritytreewindow authoritytreeview' : {
				checkchange : function(record, checked) {
					if (!record.isLeaf()) {
						var childNodes = record.childNodes;
						Ext.Array.each(childNodes, function(childNode) {
									childNode.set('checked', checked);
								});
					}
				},
				render : function(view) {
					var me = this, record = me.getRoleview()
							.getSelectionModel().getLastSelected(), treeStore = view
							.getStore();
					if (me.authoritytreeload) {
						me.fireCheckedTrueByAuth(record, treeStore);
					}
				},
				load : function(treeStore, node, records, successful) {
					var me = this, record = me.getRoleview()
							.getSelectionModel().getLastSelected();
					me.fireCheckedTrueByAuth(record, treeStore);
				}
			},
			'authoritytreewindow button#save' : {
				click : function(btn) {
					var me = this, record = me.getRoleview()
							.getSelectionModel().getLastSelected(), treepanel = btn
							.up('window').down('treepanel'), records = treepanel
							.getView().getChecked();
					if (records.length > 0) {
						var arr = new Array();
						Ext.Array.each(records, function(rec) {
									if (rec.isLeaf()) {
										arr.push(rec.get('id'));
									}
								});
						if (arr.length > 0) {
							Ext.Ajax.request({
										url : 'role/updateAuthority',
										jsonData : Ext.encode(arr),
										params : {
											roleId : record.get('id')
										},
										success : function(response) {
											var text = response.responseText;
											if (text == 1) {
												btn.up('window').close();
												Ext.MessageBoxUtil.msg('提示',
														'操作成功!');
											} else {
												Ext.MessageBoxUtil.msg('提示',
														'操作失败!');
											}
										},
										failure : function(response, options) {
											Ext.MessageBoxUtil.msg('提示',
													'操作失败,错误编号：'
															+ response.status);
										}
									});
						}
					}
				}
			},
			'roleview button#edituser' : {
				click : function(btn) {
					var record = btn.up('roleview').getSelectionModel()
							.getLastSelected(), win = Ext.widget(
							'usergridview', {
								animateTarget : document.body
							}), grid = win.down('grid');
					win.setTitle('角色 ' + record.get('roleDescription')
							+ ' 对应的用户');
					grid.reconfigure(record.users());
					grid.getStore().load({
								scope : this,
								url : 'role/getUserByRole',
								params : {
									roleId : record.get('id')
								},
								callback : function(records, operation, success) {
									grid.getStore().removeFilter();
								}
							});
					win.show();
				}
			},
			'usergridview actioncolumn#deleteuser' : {},
			'usergridview button#searchuser' : {
				click : function(btn) {
					var win = Ext.widget('searchuserview', {
								animateTarget : document.body
							}), usergrid = btn.up('window').down('grid'), searchgrid = win
							.down('grid'), userstore = usergrid.getStore(), searchstore = searchgrid
							.getStore();
					searchstore.filter([{
								filterFn : function(item) {
									return !userstore.getById(item.get('id'));
								}
							}]);
					win.show();
				}
			},
			'searchuserview button#OK' : {
				click : function(btn) {
					var me = this, record = me.getRoleview()
							.getSelectionModel().getLastSelected(), records = btn
							.up('searchuserview').down('grid')
							.getSelectionModel().getSelection(), userstore = me
							.getUsergridview().down('grid').getStore();
					if (records.length > 0) {
						var arr = new Array();
						for (var i = 0; i < records.length; i++) {
							arr.push(records[i].getData());
						}
						Ext.Ajax.request({
									url : 'role/addUserForRole',
									jsonData : Ext.encode(arr),
									params : {
										roleId : record.get('id')
									},
									success : function(response) {
										var text = response.responseText;
										if (text == 1) {
											userstore.add(records);
											btn.up('window').close();
											Ext.MessageBoxUtil.msg('提示',
													'增加成功!');
										} else {
											Ext.MessageBoxUtil.msg('提示',
													'增加失败!');
										}
									},
									failure : function(response, options) {
										Ext.MessageBoxUtil.msg('提示',
												'操作失败,错误编号：' + response.status);
									}
								});
					}
				}
			},
			'roleview button#add' : {
				click : function(btn) {
					this.onAddButtonClick('roleform');
				}
			},
			'roleform button#save' : {
				click : function(btn) {
					var me = this;
					me.onSaveButtonClick(btn, me.getRoleStoreStore(), me
									.getRoleEntityModel());
				}
			},
			'roleview button#update' : {
				click : function(btn) {
					this.onEditButtonClick(btn, 'roleview', 'roleform');
				}
			}
		});
	},
	fireCheckedTrueByAuth : function(record, treeStore) {
		var me = this;
		me.fireCheckedFalse(treeStore.getRootNode());
		Ext.Ajax.request({
					url : 'role/getAuthoritiesByRole',
					params : {
						roleId : record.get('id')
					},
					async : false,// 同步请求数据
					success : function(response) {
						var auths = Ext.decode(response.responseText);
						if (auths.length > 0) {
							Ext.Array.each(auths, function(auth) {
										treeStore.getNodeById(auth.id).set(
												'checked', true);
									});
						}
						me.authoritytreeload = true;
					},
					failure : function(response, options) {
						Ext.MessageBoxUtil.msg('提示', '操作失败,错误编号：'
										+ response.status);
					}
				});
	},
	fireCheckedFalse : function(rootnode) {
		var me = this;
		if (!rootnode.isLeaf()) {
			var childNodes = rootnode.childNodes;
			if (childNodes.length > 0) {
				Ext.Array.each(childNodes, function(childNode) {
							if (!childNode.isLeaf()) {
								me.fireCheckedFalse(childNode);
							}
							childNode.set('checked', false);
						});
			}
		}
	}
});